package com.kuang.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {

    //编写自定义配置类
    //Redis默认使用jdk实现序列化，jdk序列化时会出现乱码

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        //  使用fastJson实现对于对象的序列化
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        //  设置"值"的序列号方式
        template.setValueSerializer(serializer);

        //  设置"hash"类型的数据的序列化方式
        template.setHashValueSerializer(serializer);

        //  设置"key"的序列化方式
        template.setKeySerializer(new StringRedisSerializer());

        //  设置"hash的key"的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());

        //  设置redis模版的工厂对象
        template.setConnectionFactory(redisConnectionFactory);

        return template;
    }
}
